package com.sunxd.zstudy.mybatise.domain.service.engine.handler.condition;

import com.sunxd.zstudy.mybatise.domain.annotation.Handler;
import com.sunxd.zstudy.mybatise.domain.contans.enums.ConditionType;
import com.sunxd.zstudy.mybatise.domain.contans.enums.OperatorType;
import com.sunxd.zstudy.mybatise.domain.dto.Condition;
import com.sunxd.zstudy.mybatise.domain.dto.Context;
import com.sunxd.zstudy.mybatise.domain.exception.CoreEngineException;
import com.sunxd.zstudy.mybatise.domain.service.engine.handler.helper.DefaultConditionHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;

/**
 */
@Component
@Handler(conditionType = ConditionType.VALUE, operatorType = OperatorType.IN)
public class InConditionHandler implements ConditionHandler {

    private final DefaultConditionHelper conditionHelper;

    @Autowired
    public InConditionHandler(DefaultConditionHelper conditionHelper) {
        this.conditionHelper = conditionHelper;
    }

    @Override
    public Boolean judge(Condition condition, Context context) {
        Optional<Object> optional = context.get((String) condition.getLeft());
        if (!optional.isPresent()) {
            return Boolean.FALSE;
        }
        Object value = optional.get();
        if (!Objects.equals(condition.getOperator(), OperatorType.IN)) {
            throw new CoreEngineException("InConditionHandler.typeNotMatch", "");
        }
        return conditionHelper.in(condition.getRight(), value);
    }
}
